<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>设备管理</span>
      <div>
        <!-- <el-button type="primary">导入设备</el-button> -->
        <el-button type="primary" @click="addfacility">添加设备</el-button>
        <el-button icon="el-icon-refresh" @click="refresh()"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <!-- <div class="leftitem">
            <div class="block">
              <el-date-picker
                v-model="conditions.stardate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="提交起始时间"
              ></el-date-picker>
              <el-date-picker
                v-model="conditions.enddate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="提交结束时间"
              ></el-date-picker>
            </div>
          </div> -->
          <div class="leftitem">
            <el-select
              class="servicelevel"
              v-model="conditions.deviceType"
              placeholder="设备类型"
            >
              <el-option keys="1" label="云喇叭" value="1"></el-option>
              <el-option keys="2" label="云打印机" value="2"></el-option>
            </el-select>
            <el-select
              class="servicelevel"
              v-model="conditions.status"
              placeholder="绑定状态"
            >
              <el-option keys="1" label="已绑定" value="0"></el-option>
              <el-option keys="2" label="未绑定" value="99"></el-option>
            </el-select>
          </div>
          <div class="leftitem">
              <el-input class="merchants" @keyup.enter.native='soso' v-model.trim="conditions.deviceNo" placeholder="设备号"></el-input>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem">
            <el-input class="merchants" @keyup.enter.native='soso' v-model.trim="conditions.keywords" placeholder="商户号/商户名/商户简称"></el-input>
          </div>
          <div class="rightitem">
            <el-input class="merchants" @keyup.enter.native='soso' v-model.trim="conditions.searchwords" placeholder="门店号/门店名"></el-input>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="soso">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>

      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="devicearr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号"></el-table-column>
          <el-table-column prop="deviceNo" label="设备号"></el-table-column>
          <el-table-column prop="deviceType" label="设备类型/品牌"></el-table-column>
          <el-table-column prop="bindingTypeName" label="绑定类型"></el-table-column>
          <el-table-column prop="bingdingNo" label="绑定编号"></el-table-column>
          <el-table-column  label="所属商户/门店">
            <template slot-scope="scope">
                <div>{{scope.row.merchantName}}<span v-if="scope.row.shopName">/</span>{{scope.row.shopName}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="merchantShortName" label="商户简称"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column label="绑定状态">
             <template slot-scope="scope">
               <div v-if="scope.row.status == 0" style="color:green">已绑定</div>
               <div v-if="scope.row.status == 99" style="color:red">未绑定</div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.status == 99" size="small" @click="bindBtn(scope.row.id)">绑定</el-button>
              <el-button type="text" v-if="scope.row.status == 0" size="small" @click="deviceremove(scope.row.id)">解绑</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            :current-page.sync="cur_page"
            @size-change="sizechange"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>
      <!-- 添加设备 -->
      <el-dialog v-dialogDrag title="添加设备" :visible.sync="eqma" width="45%" :close-on-click-modal="false">
        <el-form
          :model="facility"
          status-icon
          ref="facility"
          label-width="110px"
          class="demo-dynamic wid100"
        >
          <el-form-item label="设备类型">
            <el-select class="wid100" v-model="facility.deviceType" placeholder="请选择" @change="deviceType(facility.deviceType)">
              <!-- <el-option v-for="(item,index) in facilitylist" :key="index" :label="item.name" :value="1"></el-option> -->
              <el-option keys="1" label="云喇叭" value="1"></el-option>
              <el-option keys="1" label="云打印机" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="绑定类型">
            <el-select class="wid100" v-model="facility.bindingType" placeholder="请选择">
              <el-option keys="1" label="商户" value="1"></el-option>
              <el-option keys="1" label="门店" value="2"></el-option>
              <!-- <el-option keys="1" label="终端" value="3"></el-option> -->
            </el-select>
          </el-form-item>
           <el-form-item label="所属终端"  v-if="facility.bindingType == 3">
              <el-input type="text" v-model.trim="facility.bingdingNo" autocomplete="off"></el-input>
           </el-form-item>
         <el-form-item  label="绑定商户" v-if="facility.bindingType == 1 || facility.bindingType == 2 " >

          <el-autocomplete class="wid100" v-model.trim="facility.merchantId" :fetch-suggestions="allmerchants" :debounce="300" placeholder="商户名" @select="marid"></el-autocomplete>
          </el-form-item>
          <el-form-item label="绑定门店" v-if="facility.bindingType == 2" >
            <el-autocomplete
            class="wid100"
              v-model.trim="facility.shopName"
              :fetch-suggestions="allshops"
              @select="shopid"
            ></el-autocomplete>
          </el-form-item>

          <el-form-item label="设备品牌">
            <el-select  class="wid100" v-model="facility.deviceBrand" placeholder="请选择" @change="deviceBrand">
              <el-option v-for="(item,index) in brand" :key="index" :label="item.name" :value="item.code"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备型号">
            <!-- <el-input type="text" v-model="facility.deviceModel" autocomplete="off"></el-input> -->
             <el-select  class="wid100" v-model="facility.deviceModel" placeholder="请选择">
              <el-option v-for="(item,index) in devicetypelist" :key="index" :label="item.name" :value="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备ID">
            <el-input type="text" v-model.trim="facility.deviceNo" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="eqma = false">取消</el-button>
          <el-button type="primary" @click="devicesave()">确定</el-button>
        </span>
      </el-dialog>
      <!-- 绑定设备 -->
      <el-dialog v-dialogDrag title="绑定设备" :visible.sync="bind" width="45%" :close-on-click-modal="false">
        <el-form
          :model="bindarr"
          status-icon
          ref="bindarr"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item label="设备类型">
            <el-select class="wid100" v-model="bindarr.deviceType" placeholder="请选择">
              <el-option keys="1" label="云喇叭" value="1"></el-option>
              <el-option keys="1" label="云打印机" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="绑定类型">
            <el-select class="wid100" v-model="bindarr.bindingType" placeholder="请选择">
              <el-option keys="1" label="商户" value="1"></el-option>
              <el-option keys="1" label="门店" value="2"></el-option>
              <!-- <el-option keys="1" label="终端" value="3"></el-option> -->
            </el-select>
          </el-form-item>
          <el-form-item  label="绑定商户" v-if="bindarr.bindingType == 1 || bindarr.bindingType == 2 " >
            <!-- <el-autocomplete
              class="wid100"
              v-model="bindarr.merchantId"
              :fetch-suggestions="allmerchants"
              @select="marid"
            ></el-autocomplete> -->
            <el-autocomplete class="wid100" v-model.trim="bindarr.merchantId" :fetch-suggestions="allmerchants1" :debounce="300" placeholder="商户名" @select="marid"></el-autocomplete>
          </el-form-item>
          <el-form-item label="绑定门店" v-if="bindarr.bindingType == 2" >
            <el-autocomplete
              class="wid100"
              v-model.trim="bindarr.shopName"
              :fetch-suggestions="allshops"
              @select="shopid"
            ></el-autocomplete>
          </el-form-item>
         
          <el-form-item label="绑定终端" v-if="bindarr.bindingType == 3">
            <el-input type="text" v-model.trim="bindarr.address" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="bind = false">取消</el-button>
          <el-button type="primary" @click="devicebind()">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getservice, merchantlist,devicepage,devicesave,devicebind,merchantall,shopall,deviceremove ,getDeviceType,inventoryCategorylist} from "@/api/api";
export default {
  name: "item-one",
  data: function() {
    return {
      tableData: [],
      cur_page: 1,
      cur_size: 10,
      multipleSelection: [],
      visible: false,
      devicearr: [],
      devicetypelist:[],
      combined: 10,
      pageCount: "",
      eqma: false,
      bind: false,
      bindid:"",
      bindarr: {},
      facility: {
        deviceBrand : '',
        // deviceType: '',
        // bindingType: '',
        // bingdingNo: '',
        // merchantId: '',
        // deviceModel: '',
        // deviceNo: '',
        // shopName: '',
      },
      allmerchant: [],
      allshop: [],
      facilitylist:[],
      brand:[],
      conditions: {
        deviceType : "",
        state : "",
        searchwords : "",
        deviceNo : "",
        keywords : ""
      }
    };
  },
  created() {
    this.$store.dispatch("getNewNum", 6);
    // console.log(this.$store.state.changableNum);
    // console.log(this.$store.state.showFooter);
    // console.log(this.$store.state.logininfo);

    this.devicepage();
  },
  methods: {
    //修改thead 背景色
      tableHeaderColor({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;'
      }
    },
    // 刷新
    refresh() {
      this.$router.replace({
        path: "/refresh",
        query: {
          t: Date.now()
        }
      });
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.devicepage();
      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    // 分页数量
    sizechange(val) {
      this.cur_size = val;
      this.devicepage();

      this.$nextTick(() => {
        document.querySelectorAll(".content")[0].scrollTop = "0";
      });
    },
    //多选框
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val;
    },
    //  重置
    reset() {
      this.conditions.deviceType = "";
      this.conditions.status = "";
      this.conditions.deviceNo = "";
      this.conditions.keywords = "";
      this.conditions.searchwords = "";
      // this.cur_page = '1'
    },
    // 搜索
    soso() {
      // if (this.conditions.servicelevel == 1) {
      //   this.devicepage("agent1Id");
      // } else if (this.conditions.servicelevel == 2) {
      //   this.devicepage("agen2Id");
      // } else {
      //   this.devicepage("agent1Id");
      // }
      this.cur_page = 1
      this.devicepage()
      
    },
     // 所有商户
    merchant(level) {
      merchantall({}).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          for (var i = 0; i < res.data.rows.length; i++) {
            this.allmerchant.push({
              value: res.data.rows[i].merchantName,
              id: res.data.rows[i].id,
              marid: res.data.rows[i].merchantNo
            });
          }
        }
      });
    },
    marid(item) {
      console.log(item)
      this.bindarr.mchId = item.id;
      this.bindarr.bingdingNo = item.marid
      this.facility.mchId = item.id;
      this.facility.bingdingNo = item.marid;
      this.shopall();
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) !==
          -1
        );
      };
    },
    // 全部商户
    allmerchants(queryString, cb) {
      // let allmerchant = this.allmerchant;
      // let results = queryString
      //   ? allmerchant.filter(this.createFilter(queryString))
      //   : allmerchant;
      // // 调用 callback 返回建议列表的数据
      // cb(results);

      let sosolist = {};
      sosolist = {
        page: 1,
        size: 20,
        merchantName: this.facility.merchantId,
      };
      merchantlist(sosolist).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
           this.merchantarrlist = []
          for(var i=0;i<res.data.length;i++){
            this.merchantarrlist.push({'value':res.data[i].merchantName,'id':res.data[i].id,'marid':res.data[i].merchantNo})
          }
           let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      })

    },
    //  全部商户绑定
    allmerchants1(queryString, cb) {
      let sosolist = {};
      sosolist = {
          page: 1,
          size: 20,
          merchantName: this.bindarr.merchantId,
        };
      merchantlist(sosolist).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
           this.merchantarrlist = []
          for(var i=0;i<res.data.length;i++){
            this.merchantarrlist.push({'value':res.data[i].merchantName,'id':res.data[i].id,'marid':res.data[i].merchantNo})
          }
           let results = queryString
            ? this.merchantarrlist.filter(this.createFilter(queryString))
            : this.merchantarrlist;
          // 调用 callback 返回建议列表的数据
          cb(results);
        }
      })

    },
    // 全部门店
    allshops(queryString, cb) {
      let allshope = this.allshop;
      let results = queryString
        ? allshope.filter(this.createFilter(queryString))
        : allshope;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    shopid(item) {
      this.bindarr.bingdingNo = item.code;
      this.facility.bingdingNo = item.code;
      this.bindarr.shopName = item.value;
    },
    // 通过商户获取门店
    shopall() {
      this.allshop = []
      shopall({
        merchantId: this.bindarr.mchId
      }).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage.removeItem("token");
          this.$router.push("/login");
        } else {
          for (var i = 0; i < res.data.rows.length; i++) {
            this.allshop.push({
              value: res.data.rows[i].shopName,
              id: res.data.rows[i].id,
              code: res.data.rows[i].shopNo
            });
          }
        }
      });
    },
    // 设备列表
    devicepage() {
      // console.log(this.conditions)
      devicepage({
        page: this.cur_page,
        size: this.cur_size,
        deviceType : this.conditions.deviceType,
        status : this.conditions.status,
        searchwords : this.conditions.searchwords,
        deviceNo : this.conditions.deviceNo,
        keywords : this.conditions.keywords
      }).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage. removeItem("token");
          this.$router.push("/login");
        } else {
          this.devicearr = res.data;
          this.combined = res.pageInfo.recordCount;
          this.pageCount = res.pageInfo.pageCount;
        }
      });
    },
    // 添加设备
    devicesave(){
      // console.log(this.facility)
       const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
       devicesave(this.facility).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage. removeItem("token");
          this.$router.push("/login");
        } else if(res.code == 200) {
          loading.close();
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.eqma =false;
          this.devicepage()
        }else{
          this.$message.error(res.message);
          loading.close();
        }
      });
    },
    // 绑定设备
    devicebind(){
      console.log(this.bindarr)
      
      devicebind(this.bindarr,this.bindid).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage. removeItem("token");
          this.$router.push("/login");
        } else if(res.code == 200){
          this.$message({
            message: "绑定成功",
            type: "success"
          });
          this.bind = false
          this.devicepage()
        }else{
          this.$message.error(res.message);
        }
      });
    },
    // 打开绑定box
    bindBtn(id){
      this.bindarr ={}
      this.bind = true
      this.bindid = id
      this.merchant();
    },
    // 解绑
    deviceremove(id){
       this.$confirm("是否确定解绑？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
         deviceremove({},id).then(res => {
            // console.log(res);
            if (res.code == 405) {
              sessionStorage. removeItem("token");
              this.$router.push("/login");
            } else if(res.code == 200){
              this.$message({
                message: "解绑成功",
                type: "success"
              });
              this.bind = false
              this.devicepage()
            }else{
              this.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });

      
    },
    // 打开添加设备box
    addfacility(){
      this.eqma = true;
      this.facility = {};
      // this.getDeviceType(); //获取设备类型
      this.merchant();
    },
    // 获取设备类型
    getDeviceType(){
      getDeviceType().then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage. removeItem("token");
          this.$router.push("/login");
        } else if(res.code == 200) {
          console.log(res)
          this.facilitylist = res.data
        }else{
        }
      });
    },
     // 获取设备品牌
    inventoryCategorylist(pid){
      let _this = this;
      inventoryCategorylist({pid:pid}).then(res => {
        // console.log(res);
        if (res.code == 405) {
          sessionStorage. removeItem("token");
          this.$router.push("/login");
        } else if(res.code == 200) {
          console.log(res)
          this.brand = res.data
        }else{
        }
      });
    },
    // 设备类型
    deviceType(e){
      let _this= this;
      _this.brand = []
      _this.$set(this.facility,'deviceBrand','')
      if(e == 1){
        this.inventoryCategorylist('1003')
      }else if(e == 2){
        this.inventoryCategorylist('1004')
      }
    },
    // 获取设备品牌获取设备型号
    deviceBrand(val){
      let _this = this;
      _this.devicetypelist = []
      _this.$set(this.facility,'deviceModel','')
      let obj = {};
        obj = this.brand.find(item => {
        //这里的userList就是上面遍历的数据源
        return item.code === val; //筛选出匹配数据
        });
        console.log(obj)
        inventoryCategorylist({pid:obj.id}).then(res => {
          if (res.code == 405) {
            sessionStorage. removeItem("token");
            this.$router.push("/login");
          } else if(res.code == 200) {
            // console.log(res)
            this.devicetypelist = res.data
          }else{
          }
        });
    }
  }
};
</script>
<style scoped lang='less'>
.title {
  background: #fff;
  padding: 10px 10px;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
}
.name {
  width: 25%;
}
.screeningBox {
  width: 100%;
  display: flex;
}
.leftBox,
.rightBox {
  width: 50%;
  padding: 0 15px;
  box-sizing: border-box;
}
.leftBox > .leftitem {
  margin-bottom: 15px;
}
.rightBox > .rightitem {
  margin-bottom: 15px;
}
.merchants {
  width: 50%;
}
.tableBox {
  margin-top: 20px;
}
.servicename {
  width: 60%;
}
.servicelevel {
  width: 20%;
}
.width20 {
  width: 20%;
}
.red {
  color: #f9607d;
}
.blue {
  color: #01aaef;
}
.stitle {
  padding: 5px 0;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  i {
    margin-left: 10px;
    margin-right: 5px;
  }
  .swarning {
    color: red;
  }
  .warning {
    color: #f9607d;
  }
}
.wid100{
  width: 100% !important;
}
</style>